package com.example.usbfileutils

import android.util.Log
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.nio.channels.FileChannel
import java.util.concurrent.CountDownLatch


class FileCopyTask(
    val srcFile: File, val destFile: File
) : Runnable {

    var countDownLatch: CountDownLatch? = null

    companion object {
        private val TAG = "FileCopyTask"
    }

    override fun run() {

        try {
            Log.d(TAG, "start copy file ${srcFile.name} to ${destFile.name}")
            copyFile(srcFile, destFile)
            Log.d(TAG, "end copy ${srcFile.name} Successfully")

        } catch (e: IOException) {
            Log.e(TAG, "error copying! ${srcFile.absolutePath}", e)
        } finally {
            countDownLatch?.countDown()
        }
    }

    // 复制文件
    private fun copyFile(srcFile: File, destFile: File) {

        val inChannel: FileChannel = FileInputStream(srcFile).getChannel()
        val outChannel: FileChannel = FileOutputStream(destFile).getChannel()

        try {
            inChannel.transferTo(0, inChannel.size(), outChannel)
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            inChannel.close()
            outChannel.close()
        }
    }

    @Throws(IOException::class)
    private fun copyStream(inputStream: InputStream, outputStream: OutputStream) {
        val buffer = ByteArray(1024)
        var length: Int
        while ((inputStream.read(buffer).also { length = it }) > 0) {
            outputStream.write(buffer, 0, length)
        }
    }
}